package com.laundry.laundry.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laundry.laundry.execption.LoginFailedException;
import com.laundry.laundry.mapper.UserMapper;
import com.laundry.laundry.properties.JwtProperties;
import com.laundry.laundry.service.UserService;
import com.laundry.laundry.utils.JwtUtil;
import com.laundry.laundrypo.dto.LoginDTO;
import com.laundry.laundrypo.entity.Customer;
import com.laundry.laundrypo.vo.LoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, Customer> implements UserService {

    private final JwtProperties jwtProperties;

    private final JwtUtil jwtUtil;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        String username = loginDTO.getName();
        String phone = loginDTO.getPhone();

        Customer customer = lambdaQuery().eq(Customer::getName, username).one();
        if(customer == null){
            throw new LoginFailedException("该用户不存在");
        }
        if(!customer.getPhone().equals(phone)){
            throw new LoginFailedException("电话号码错误");
        }
        //生成token
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("phone", phone);

        String token = jwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), map);
        //返回vo
        // 6.封装VO返回
        LoginVO vo = new LoginVO();
        vo.setCustomerId(customer.getId());
        vo.setCustomerName(customer.getName());
        vo.setToken(token);
        return vo;
    }
}
